package com.tueye.framework.core.template.support;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import freemarker.cache.TemplateLoader;

/**
 * 类说明：模板资源加载
 * 
 * @author hanxiaowei
 * 
 */
public class FrameworkTemplateLoader implements TemplateLoader {

	private final Log logger = LogFactory.getLog(getClass());

	private final ResourceLoader resourceLoader;
	private final String templateLoaderPath;

	/**
	 * 创建一个新的FreeMarker模板
	 * 
	 * @param resourceLoader
	 *            the Spring ResourceLoader to use
	 * @param templateLoaderPath
	 *            the template loader path to use
	 */
	public FrameworkTemplateLoader(ResourceLoader resourceLoader,
			String templateLoaderPath) {
		this.resourceLoader = resourceLoader;
		if (!templateLoaderPath.endsWith("/")) {
			templateLoaderPath += "/";
		}
		this.templateLoaderPath = templateLoaderPath;
		logger.info("模板组件: 使用的资源加载器 [" + this.resourceLoader + "] 模板加载路径 ["
				+ this.templateLoaderPath + "]");
	}

	@Override
	public void closeTemplateSource(Object arg0) throws IOException {
		// 暂不激活

	}

	@Override
	public Object findTemplateSource(String name) throws IOException {

		logger.debug("查找的模板名称 [" + name + "]");
		Resource resource = this.resourceLoader
				.getResource(this.templateLoaderPath + name);
		return (resource.exists() ? resource : null);
	}

	@Override
	public long getLastModified(Object arg0) {

		return -1;
	}

	@Override
	public Reader getReader(Object templateSource, String encoding)
			throws IOException {

		Resource resource = (Resource) templateSource;
		try {
			return new InputStreamReader(resource.getInputStream(), encoding);
		} catch (IOException ex) {
			logger.error("查找模板资源文件出错,模板" + ex);
			return null;
		}
	}

}
